package com.tosmart.jorm.cases;

import com.tosmart.jorm.models.Family;
import org.testng.Assert;
import org.testng.annotations.*;

import java.sql.SQLException;

/**
 * Date: 2009-12-30
 * Time: 16:01:27
 *
 * @author tosmart@gmail.com
 */
public class OptimisticLock extends TestBase {

    @BeforeTest
    protected void setUp() throws SQLException {

        super.setUp();

        Family family = new Family(1);
        family.setName("tosmart family");
        family.setAddress("ChongQing China.");
        family.setBalance(10000D);

        jormFace.insertEntity(family);
    }

    @AfterTest
    protected void tearDown() throws SQLException {
        super.tearDown();
    }

    @Test
    public void test() {

        Family refer1 = jormFace.loadEntity(Family.class, 1);
        Family refer2 = jormFace.loadEntity(Family.class, 1);

        refer1.setBalance(refer1.getBalance() - 2000D);
        refer2.setBalance(refer2.getBalance() + 3000D);

        try {
            jormFace.updateEntity(refer1);
            jormFace.updateEntity(refer2);
            Assert.assertFalse(true);
        }
        catch (Exception e) {
            Assert.assertTrue(
                    e.getMessage().indexOf(
                            "Lock Object is Changed"
                    ) > -1
            );
        }

        Family family = jormFace.loadEntity(Family.class, 1);
        Assert.assertNotNull(family);

        Assert.assertEquals(family.getBalance(), 8000D);
    }
}
